// SlagCar/DriverRegisterDetl/DriverRegisterDetl.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    system_id: 1164,
    fieldList: [],  //司机信息字段
    rowData: {},

    fields: [
      //【车属单位】改名为【架构公司】
      {label: '架构公司',field_id: 'cheshudanwei_id',type: 'reference1',mainEntity: 'all_department',showFields: 'department_name',is_null: false, referenceFilterCondition: "{\"filters\":[{\"filterType\":\"text\",\"type\":\"text\",\"fieldName\":\"parent_department_id\",\"value\":\"\",\"operator\":\"is null\"}],\"type\":\"AND\"}", },  // 231216 liang 增加 referenceFilterCondition 默认显示 冠力、方通公司
      //【部署至部门】改名为【架构部门】
      {label: '架构部门',field_id: 'to_department_id',type: 'reference1',mainEntity: 'all_department',showFields: 'department_name',is_null: false},
      {label: '车辆用途',field_id: 'cheliangyongtu',type: 'picklist',is_null: false,option: '[{"label":"运输车辆","isDefault":true},{"label":"流动油车","isDefault":false},{"label":"商务车辆","isDefault":false},{"label":"挖机","isDefault":false},{"label":"吊机","isDefault":false},{"label":"推土机","isDefault":false},{"label":"其它","isDefault":false},{"label":"洒水车","isDefault":false}]'},
      //【车辆经营者】改名为【车辆实际经营主体】
      {label: '车辆实际经营主体',field_id: 'Order_client_id',type: 'reference1',mainEntity: 'customer',showFields: 'customer_name',is_null: false, referenceFilterCondition: "{\"filters\":[{\"filterType\":\"bit\",\"type\":\"bit\",\"fieldName\":\"cheliangjingyingzhe\",\"value\":true,\"operator\":\"=\"}],\"type\":\"AND\"}", },  // 231218 liang 审核增加车辆经营者资料的选择
      //增加车辆经营主体（承运人），引用往来单位的是承运单位过滤，必填
      {label: '车辆经营主体',field_id: 'chengyundanwei_id',type: 'reference1',mainEntity: 'customer',showFields: 'customer_name',is_null: false, referenceFilterCondition: "{\"filters\":[{\"filterType\":\"bit\",\"type\":\"bit\",\"fieldName\":\"cheshudanwei\",\"value\":true,\"operator\":\"=\"}],\"type\":\"AND\"}", },
      //增加经营性质
      {label: '经营性质',field_id: 'jingyingxingzhi_id',type: 'reference1',mainEntity: 'e_jingyingxingzhibiao',showFields: 'jingyingxingzhi',is_null: false, referenceFilterCondition: "{\"filters\":[{\"filterType\":\"bit\",\"type\":\"bit\",\"fieldName\":\"is_used\",\"value\":true,\"operator\":\"=\"}],\"type\":\"AND\"}", },
      {label: '所属车队',field_id: 'suoshuchedui_id',type: 'reference1',mainEntity: 'e_cheduiguanli',showFields: 'cheduimingchen',is_null: false, referenceFilterCondition: "", },
      {label: '所属分队',field_id: 'suoshufendui_id',type: 'reference1',mainEntity: 'e_fenduiguanli',showFields: 'fenduimingchen',is_null: true, referenceFilterCondition: "", },
    ], //开通账号字段
    formData: {},
    show: false,


    disabled: true,

    // 231218 liang 退审相关
    refundShow: false,
    refundFields: [
      {label: '退审原因',field_id: 'reason',type: 'textarea',is_null: false},
    ],
    refundForm: {
      reason: '',
    },
    refundValidFlag: false,

    // 231218 end
  },

  bindClose(){
    this.setData({show: false})
  },
  bindShow(){
    this.setData({show: true})
  },

  getRowData(id){
    let {system_id,miniprogram_OpenID} = this.data;
    wx.showLoading()
    wx.$get(5,`ZT/DriverRegistration/${system_id}?row_id=${id}`).then(res => {
      if (res.errcode != 0) return;
      wx.hideLoading();
      let data = res.data.row[0] || {};
      this.setData({rowData: data})
    })
  },

  // 记录验证表单项
  validIpt(e) {
    let { validObj, } = this.data
    this.data.validObj = {
      ...validObj,
      ...e.detail,
    };
  },
  //验证数据
  validForm(validObj){
    return new Promise((resolve, reject) => {
      let valid = Object.values(validObj).includes(false) ? false : true;
      resolve(valid)
    })
  },
  //字段修改
  bindChange(e){
    let detail = e.detail,
      field = detail.field,
      id = field.field_id || field.fieldName,
      type = field.type,
      val = detail.val;

    if (type === 'num' || type === 'currency' || type === 'percent'){
      val = val ? val : null
    }
    if (id === 'to_department_id') {
      console.log(e);
    }

    //赋值
    this.data.formData[id] = val;
  },

  onSubmit(){
    let {formData,rowData,system_id,} = this.data;

    this.data.validObj = {}
    this.setData({
      validFlag: !this.data.validFlag,
    });
    let validObj = this.data.validObj;

    this.validForm(validObj).then(async valid => {
      if(valid) { // 表单验证通过
        console.log('表单验证通过', formData);
        wx.showLoading({mask: true});

        let post = {...formData,row_id: rowData.row_id || 0}

        wx.$post(5,`ZTAuth/VerifiedDriverRegistration`,post).then(res =>{
          if (res.errcode != 0) return;
          wx.$toast('开通成功');
          this.setData({show: false})
          this.getRowData(rowData.row_id);
        })


      } else {  // 表单验证不通过
        console.log('表单验证不通过')
        wx.$toast('必填项不能为空！')
      }
    })
  },


  //获取模块字段
  getCustomField(table_id){
    let url = 'QX/PRO_select_field',
      post = {"table": table_id,"fieldname":""};
    return new Promise(resolve => {
      wx.$post(4,url,post).then(res =>{
        if (res.errcode != 0) return;
        let data = res.data.row || [];
        resolve(data);
      })
    })
  },

  prepare(options){
    wx.showLoading({mask: true})
    this.getCustomField('e_driver_registration').then(res => {
      wx.hideLoading();
      let fields = ['name','driver_type','phone','vehicle_no','fuwudanweiquanchen','idcard_no','idcard_front','idcard_back','driver_license_no','driver_license_pic','certificate_no','certificate_pic','driving_permit_no','driving_permit_pic','operating_permit_no','operating_permit_pic','business_license_pic','driver_profile_photo','vehicle_pic','vehicle_number_pic','vehicle_lightbox_pic','deposit_bank','invoicing_information','is_Checked',],
        fieldList = [];
      fields.forEach(item =>{
        fieldList.push(res.find(ite => item === ite.field_id))
      });
      this.setData({fieldList})
    })
    let {row_id} = options;
    this.getRowData(row_id)

  },

  // 231218 liang 退审相关
  onRefundShow() {
    this.onRefundShowToggle(true)
  },
  onRefundClose() {
    this.onRefundShowToggle(false)
  },
  onRefundShowToggle(bool) {
    this.setData({
      refundShow: bool,
    })
  },
  onRefundChange(e) {
    let detail = e.detail,
        field = detail.field,
        id = field.field_id || field.fieldName,
        type = field.type,
        val = detail.val
    console.log(id, val)
    this.data.refundForm[id] = val;
  },
  async onRefundSubmit() {
    await new Promise(resolve => {
      let timer = setTimeout(() => {
        resolve()
        clearTimeout(timer)
      }, 150)
    })
    let { refundForm, rowData, system_id, refundValidFlag, } = this.data

    console.log(refundForm)
    this.data.refundValidObj = {}
    this.setData({
      refundValidFlag: !refundValidFlag,
    })
    let refundValidObj = this.data.refundValidObj

    this.onRefundValidForm(refundValidObj).then(valid => {
      if(valid) {
        wx.showLoading({ mask: true, })
        let post = {
          ...refundForm,
          row_id: rowData.row_id || 0,
        }
        wx.$post(5, `ZTAuth/DisapproveDriverRegistration`, post).then(res => {
          wx.hideLoading()
          if(res.errcode != 0) return
          this.setData({ refundShow: false, })
          this.getRowData(rowData.row_id)
          wx.$toast('退审成功！')
        })
      } else {
        wx.$toast('必填项不能为空！')
      }
    })
  },
  onRefundValidIpt(e) {
    let { refundValidObj, } = this.data
    this.data.refundValidObj = {
      ...refundValidObj,
      ...e.detail,
    }
  },
  onRefundValidForm(validObj) {
    return new Promise((resolve, reject) => {
      let valid = Object.values(validObj).includes(false) ? false : true;
      resolve(valid)
    })
  },
  // 231218 end

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.prepare(options);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
